const app = getApp();

Page({
  data: {
    qrcodeId: '',
    userInfo: null,
    hasUserInfo: false,
    showLoginButton: true,
    showDetails: false
  },

  onLoad: function(options) {
    if (options.qrcodeId) {
      this.setData({
        qrcodeId: options.qrcodeId
      });
      console.log('获取到二维码ID:', options.qrcodeId);
    }

    // 检查登录状态
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,
        showLoginButton: false
      });
    }
  },

  // 处理登录
  handleLogin() {
    wx.showLoading({
      title: '登录中...',
    });

    // 调用全局登录方法
    getApp().login()
      .then(userInfo => {
        this.setData({
          userInfo: userInfo,
          hasUserInfo: true,
          showLoginButton: false
        });
        wx.hideLoading();
        wx.showToast({
          title: '登录成功',
          icon: 'success'
        });
      })
      .catch(err => {
        console.error('登录失败', err);
        wx.hideLoading();
        wx.showToast({
          title: '登录失败',
          icon: 'error'
        });
      });
  },

  // 确认登录
  handleConfirmLogin() {
    if (!this.data.hasUserInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '确认登录中...',
    });

    // 获取后端服务地址
    const serverUrl = app.globalData.serverUrl;
    console.log('发送确认登录请求，二维码ID:', this.data.qrcodeId);

    // 发送确认登录请求
    wx.request({
      url: `${serverUrl}/api/scan/confirm`,
      method: 'POST',
      data: {
        qrcodeId: this.data.qrcodeId,
        userInfo: this.data.userInfo
      },
      success: (res) => {
        wx.hideLoading();
        console.log('确认登录响应:', res.data);
        if (res.statusCode === 200 && res.data.success) {
          wx.showToast({
            title: '登录成功',
            icon: 'success'
          });
          // 返回上一页
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.message || '登录失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('确认登录请求失败:', err);
        wx.hideLoading();
        
        // 显示详细错误信息
        let errorMsg = '登录失败，请重试';
        if (err.errMsg.includes('request:fail')) {
          errorMsg = '无法连接到服务器，请检查：\n1. 后端服务是否启动\n2. 服务器地址是否正确\n3. 是否配置了HTTPS\n4. 是否在开发工具中勾选"不校验合法域名"';
        }
        
        wx.showModal({
          title: '网络错误',
          content: errorMsg,
          showCancel: false
        });
      }
    });
  },

  // 切换用户详情显示
  toggleDetails() {
    this.setData({
      showDetails: !this.data.showDetails
    });
  },

  // 复制用户信息
  copyUserInfo() {
    const userInfo = this.data.userInfo;
    if (!userInfo) return;
    
    const userInfoText = JSON.stringify({
      nickName: userInfo.nickName || '未获取',
      gender: userInfo.gender === 1 ? '男' : (userInfo.gender === 2 ? '女' : '未知'),
      code: userInfo.code || '未获取',
      province: userInfo.province || '',
      city: userInfo.city || ''
    }, null, 2);
    
    wx.setClipboardData({
      data: userInfoText,
      success: () => {
        wx.showToast({
          title: '用户信息已复制',
          icon: 'success'
        });
      }
    });
  }
}); 